package com.lvmama.rhino.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lvmama.rhino.entity.ButtonName;
import com.lvmama.rhino.entity.PieRobot;
import com.lvmama.rhino.entity.RobotButton;
import com.lvmama.rhino.mapper.AskAnswerStatMapper;
import com.lvmama.rhino.mapper.ButtonClickMapper;
import com.lvmama.rhino.mapper.FrequentlyQuestionMapper;
import com.lvmama.rhino.mapper.PageVisitMapper;
import com.lvmama.rhino.mapper.SourceVisitMapper;
import com.lvmama.rhino.pojo.AskAnswerStat;
import com.lvmama.rhino.pojo.ButtonClick;
import com.lvmama.rhino.pojo.FrequentlyQuestion;
import com.lvmama.rhino.pojo.PageVisit;
import com.lvmama.rhino.pojo.ResponseRobot;
import com.lvmama.rhino.pojo.RobotData;
import com.lvmama.rhino.pojo.SourceVisit;
import com.lvmama.rhino.service.RobotService;
import com.lvmama.rhino.utils.PageCodeUtil;

/**
 * 
 * @author yecan
 * @date 2016年7月22日
 */
@Service
public class RobotServiceImpl implements RobotService {
	@Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig requestConfig;
    
    @Value("${ROBOT_KEY}")
	private  String url;
	
	private static final ObjectMapper MAPPER = new ObjectMapper();
	@Autowired
	private AskAnswerStatMapper askAnswerStatMapper;
	@Autowired
	private ButtonClickMapper buttonClickMapper;
	@Autowired
	private PageVisitMapper pageVisitMapper;
	@Autowired
	private FrequentlyQuestionMapper frequentlyQuestionMapper;
	@Autowired
	private SourceVisitMapper sourceVisitMapper;

	@Override
	public RobotData queryRobotData(String province ,Date start, Date end) throws IOException {
		//数据库中创建时间要晚一天
	    Date startDate=new Date(start.getTime() + 1 * 24 * 60 * 60 * 1000);
        Date endDate=new Date(end.getTime() + 1 * 24 * 60 * 60 * 1000);
		Map<String, String> map = getButtonMap();
		RobotData robotData = new RobotData();
		//查询在线问答次数
		AskAnswerStat askAnswerStat = askAnswerStatMapper.queryData(province,startDate,endDate);
		//查询按钮点击次数
		List<ButtonClick> buttonClicksList = buttonClickMapper.queryData(province,startDate,endDate);
		//查询页面访问次数
		List<PageVisit> pageVisitsList = pageVisitMapper.queryData(province,startDate,endDate);
		//查询常见问题
		List<FrequentlyQuestion> frequentlyQuestionsList = frequentlyQuestionMapper
				.queryData(province,startDate,endDate);
		//来源页面
		List<SourceVisit> sourceVisitsList = sourceVisitMapper.queryData(province,startDate,endDate);
		robotData.setAskAnswerStat(askAnswerStat);
		List<ResponseRobot> buttonClickList = new ArrayList<>();
		//封装按钮点击次数的数据
		if (buttonClicksList != null && buttonClicksList.size()!=0) {
		    for(ButtonClick buttonClick : buttonClicksList){
		        if (buttonClick != null
	                && StringUtils.isNotBlank(buttonClick.getButtonClicks())) {
		        	String queryButtonClicks=buttonClick.getButtonClicks();
		        	queryButtonClicks=StringUtils.replace(queryButtonClicks, "[", "");
		        	queryButtonClicks=StringUtils.replace(queryButtonClicks, "]", "");
		        	
	            String[] splitButton = StringUtils.split(
	            		queryButtonClicks, ",");
	            if (splitButton != null && splitButton.length != 0) {
	                for (String string : splitButton) {
	                    String[] split = StringUtils.split(string, ":");
	                    //有些数据可能只有次数，无按钮名称的默认为空字符串
	                    if(split.length==1){
	                        String count=split[0];
	                        split=new String[2];
	                        split[0]=" ";
	                        split[1]=count;
	                    }
	                    
	                    Boolean flag=false;
                        if(buttonClickList!=null && buttonClickList.size()!=0){
                        	//去除重复数据，当集合中已经存在该按钮，叠加次数，并设置flag为true
                            for (ResponseRobot res : buttonClickList) {
                                if(res.getName().equals(split[0]) || res.getName().equals(map.get(split[0]))|| (res.getName().equals("其它")&&StringUtils.isBlank(split[0]))){
                                    flag=true;
                                    res.setCounts(res.getCounts()+Integer.valueOf(split[1]));
                                }
                            }
                        }
	                    
                        if(!flag){
    	                    ResponseRobot responseButtonClick = new ResponseRobot();
    	                    if(StringUtils.isBlank(split[0])){
    	                        responseButtonClick.setName("其它");
    	                    }
    	                    else if(map.get(split[0]) !=null){
    	                            responseButtonClick.setName(map.get(split[0]));
    	                       } else{
    	                           continue;
    	                    }
    	                    responseButtonClick.setCounts(Integer.valueOf(split[1]));
    	                    buttonClickList.add(responseButtonClick);
                        }
	                }
	            }
	        }
		    }
		}
		//按次数倒序排列
		Collections.sort(buttonClickList, new myComparator());
        Collections.reverse(buttonClickList);
		robotData.setButtonList(buttonClickList);
		//封装饼图数据
		List<PieRobot> listPie=new ArrayList<>();
		if(robotData.getButtonList()!=null && robotData.getButtonList().size()!=0){
		for (ResponseRobot responseRobot : robotData.getButtonList()) {
			PieRobot pieRobot=new PieRobot();
			pieRobot.setName(responseRobot.getName());
			pieRobot.setValue(responseRobot.getCounts());
			listPie.add(pieRobot);
		}
		}
		robotData.setButtonPie(listPie);
		List<ResponseRobot> pageVisitList = new ArrayList<>();
		//封装页面访问次数
		if(pageVisitsList !=null && pageVisitsList.size() !=0){
            for (PageVisit pageVisit : pageVisitsList) {
        		if (pageVisit != null && StringUtils.isNotBlank(pageVisit.getPageCodes())) {
        			String queryPageCodes=pageVisit.getPageCodes();
        			queryPageCodes=StringUtils.replace(queryPageCodes, "[", "");
        			queryPageCodes=StringUtils.replace(queryPageCodes, "]", "");
        			String[] splitPageVisit = StringUtils.split(queryPageCodes, ",");
        			if (splitPageVisit != null && splitPageVisit.length != 0) {
        				for (String string : splitPageVisit) {
        					String[] split = StringUtils.split(string, ":");
        					if(split.length==1){
        						String count=split[0];
        						split=new String[2];
        						split[0]=" ";
        						split[1]=count;
        					}
        					
        					Boolean flag=false;
                            if(pageVisitList!=null && pageVisitList.size()!=0){
                                for (ResponseRobot res : pageVisitList) {
                                    
                                    if(res.getName().equals(PageCodeUtil.getPageName(split[0], "/robot.properties")) ||(res.getName().equals("其它")&&StringUtils.isBlank(PageCodeUtil.getPageName(split[0], "/robot.properties")))){
                                        flag=true;
                                        res.setCounts(res.getCounts()+Integer.valueOf(split[1]));
                                    }
//                                    
                                }
                            }
                            if(!flag){
            					ResponseRobot responsePageVisit = new ResponseRobot();
            					String pageName = PageCodeUtil.getPageName(split[0], "/robot.properties");
            					if(StringUtils.isBlank(pageName)){
            						responsePageVisit.setName("其它");
            					}else{
            					responsePageVisit.setName(pageName);
            					}
            					responsePageVisit.setCounts(Integer.valueOf(split[1]));
            					pageVisitList.add(responsePageVisit);
                            }
        				}
        			}
        		}
            }
		}
		Collections.sort(pageVisitList, new myComparator());
        Collections.reverse(pageVisitList);
		robotData.setPageVisitList(pageVisitList);

		List<ResponseRobot> questionList = new ArrayList<>();
		if (frequentlyQuestionsList != null && frequentlyQuestionsList.size()!=0) {
            for(FrequentlyQuestion frequentlyQuestion : frequentlyQuestionsList){
        		if (frequentlyQuestion != null
        				&& StringUtils.isNotBlank(frequentlyQuestion.getQuestions())) {
        			String queryQuestions=frequentlyQuestion.getQuestions();
        			queryQuestions=StringUtils.replace(queryQuestions, "[", "");
        			queryQuestions=StringUtils.replace(queryQuestions, "]", "");
        			String[] questions = StringUtils.split(
        					queryQuestions, ",");
        			if (questions != null && questions.length != 0) {
        				for (String string : questions) {
        					String[] split = StringUtils.split(string, ":");
        					if(split.length==1){
        						String count=split[0];
        						split=new String[2];
        						split[0]=" ";
        						split[1]=count;
        					}
        					
        					Boolean flag=false;
                            if(questionList!=null && questionList.size()!=0){
                                for (ResponseRobot res : questionList) {
                                    if(res.getName().equals(split[0]) || res.getName().equals(map.get(split[0]))|| (res.getName().equals("其它")&&StringUtils.isBlank(split[0]))){
                                        flag=true;
                                        res.setCounts(res.getCounts()+Integer.valueOf(split[1]));
                                    }
                                }
                            }
                            
                            if(!flag){
            					ResponseRobot responseQuestion = new ResponseRobot();
            					if(StringUtils.isBlank(split[0])){
            						responseQuestion.setName("其它");
            					}else{
            						responseQuestion.setName(split[0]);
            					}
            					responseQuestion.setCounts(Integer.valueOf(split[1]));
            					questionList.add(responseQuestion);
                            }
        				}
        			}
        		}
            }
        }
		Collections.sort(questionList, new myComparator());
        Collections.reverse(questionList);
        if(questionList!=null && questionList.size()>10){
        	questionList=questionList.subList(0, 10);
        }
		robotData.setQuestionList(questionList);
		
		//封装饼图数据
		List<PieRobot> questionPie=new ArrayList<>();
		if(robotData.getQuestionList()!=null && robotData.getQuestionList().size()!=0){
		for (ResponseRobot responseRobot : robotData.getQuestionList()) {
			PieRobot pieRobot=new PieRobot();
			pieRobot.setName(responseRobot.getName());
			pieRobot.setValue(responseRobot.getCounts());
			questionPie.add(pieRobot);
		}
		}
		robotData.setQuestionPie(questionPie);
		
		List<ResponseRobot> sourceVisitList = new ArrayList<>();
		if(sourceVisitsList !=null && sourceVisitsList.size() !=0){
            for (SourceVisit sourceVisit : sourceVisitsList) {
        		if (sourceVisit != null && StringUtils.isNotBlank(sourceVisit.getPageCodes())) {
        			String queryPageCodes=sourceVisit.getPageCodes();
        			queryPageCodes=StringUtils.replace(queryPageCodes, "[", "");
        			queryPageCodes=StringUtils.replace(queryPageCodes, "]", "");
        			String[] sourcePage = StringUtils.split(queryPageCodes,
        					",");
        			if (sourcePage != null && sourcePage.length != 0) {
        				for (String string : sourcePage) {
        					String[] split = StringUtils.split(string, ":");
        					if(split.length==1){
        						String count=split[0];
        						split=new String[2];
        						split[0]=" ";
        						split[1]=count;
        					}
        					
        					Boolean flag=false;
                            if(sourceVisitList!=null && sourceVisitList.size()!=0){
                                for (ResponseRobot res : sourceVisitList) {
                                    if(res.getName().equals(PageCodeUtil.getPageName(split[0],"/robot.properties")) ||(res.getName().equals("其它")&&StringUtils.isBlank(PageCodeUtil.getPageName(split[0],"/robot.properties")))){
                                        flag=true;
                                        res.setCounts(res.getCounts()+Integer.valueOf(split[1]));
                                    }
                                }
                            }
                            
                            if(!flag){
            					ResponseRobot responseSourceVisit = new ResponseRobot();
            					String pageName = PageCodeUtil.getPageName(split[0], "/robot.properties");
            					if(StringUtils.isBlank(pageName)){
            						responseSourceVisit.setName("其它");
            					}else{
            					responseSourceVisit.setName(pageName);
            					}
            					responseSourceVisit.setCounts(Integer.valueOf(split[1]));
            					sourceVisitList.add(responseSourceVisit);
                            }
        				}
        			}
        		}
            }
		}
		Collections.sort(sourceVisitList, new myComparator());
        Collections.reverse(sourceVisitList);
		robotData.setSourceVisitList(sourceVisitList);
		robotData.setArea(province);
		robotData.setStartDate(start);
        robotData.setEndDate(end);

		return robotData;
	}
	
	
	@Override
	public RobotData queryAllData(Date start, Date end) throws IOException {
		Map<String, String> buttonMap = getButtonMap();
		RobotData robotData = new RobotData();
		//数据库中createTime要晚一天
		Date startDate=new Date(start.getTime() + 1 * 24 * 60 * 60 * 1000);
		Date endDate=new Date(end.getTime() + 1 * 24 * 60 * 60 * 1000);
		//查询在线客服问答次数
		AskAnswerStat askAnswerStat = askAnswerStatMapper.queryAllData(startDate,endDate);
		List<ButtonClick> buttonClick = buttonClickMapper.queryAllData(startDate,endDate);
		List<PageVisit> pageVisit = pageVisitMapper.queryAllData(startDate,endDate);
		List<FrequentlyQuestion> frequentlyQuestionsList = frequentlyQuestionMapper.queryAllData(startDate,endDate);
		List<SourceVisit> sourceVisit = sourceVisitMapper.queryAllData(startDate,endDate);
		
		List<ResponseRobot> buttonClickList = new ArrayList<>();
		if(buttonClick !=null && buttonClick.size() !=0){
			for (ButtonClick buttonClick2 : buttonClick) {
				if(buttonClick2!=null && StringUtils.isNotBlank(buttonClick2.getButtonClicks())){
					String queryButtonClicks=buttonClick2.getButtonClicks();
		        	queryButtonClicks=StringUtils.replace(queryButtonClicks, "[", "");
		        	queryButtonClicks=StringUtils.replace(queryButtonClicks, "]", "");
					String[] split = StringUtils.split(queryButtonClicks, ",");
					if(split !=null && split.length!=0){
						for (String string : split) {
							String[] split2 = StringUtils.split(string, ":");
							if(split2.length==1){
								String count=split2[0];
								split2=new String[2];
								split2[0]=" ";
								split2[1]=count;
							}
							Boolean flag=false;
							if(buttonClickList!=null && buttonClickList.size()!=0){
								for (ResponseRobot res : buttonClickList) {
									if(res.getName().equals(split2[0]) || res.getName().equals(buttonMap.get(split2[0]))|| (res.getName().equals("其它")&&StringUtils.isBlank(split2[0]))){
										flag=true;
										res.setCounts(res.getCounts()+Integer.valueOf(split2[1]));
									}
								}
							}
							
							if(!flag){
								ResponseRobot responseRobot=new ResponseRobot();
								if(StringUtils.isBlank(split2[0])){
									responseRobot.setName("其它");
								}
								else if(buttonMap.get(split2[0])!=null){
										responseRobot.setName(buttonMap.get(split2[0]));
								    } else{
								    	    continue;
								    	}
								responseRobot.setCounts(Integer.valueOf(split2[1]));
								buttonClickList.add(responseRobot);
							}
						}
					}
				}
			}
		}
		robotData.setAskAnswerStat(askAnswerStat);
		Collections.sort(buttonClickList, new myComparator());
        Collections.reverse(buttonClickList);
        robotData.setButtonList(buttonClickList);
        	//封装饼图数据
      		List<PieRobot> listPie=new ArrayList<>();
      		if(robotData.getButtonList()!=null && robotData.getButtonList().size()!=0){
      		for (ResponseRobot responseRobot : robotData.getButtonList()) {
      			PieRobot pieRobot=new PieRobot();
      			pieRobot.setName(responseRobot.getName());
      			pieRobot.setValue(responseRobot.getCounts());
      			listPie.add(pieRobot);
      		}
      		}
      		robotData.setButtonPie(listPie);
		
		
		List<ResponseRobot> pageVisitList = new ArrayList<>();
		if(pageVisit !=null && pageVisit.size() !=0){
			for (PageVisit pageVisit2 : pageVisit) {
				if(pageVisit2!=null && StringUtils.isNotBlank(pageVisit2.getPageCodes())){
					String queryPageCodes=pageVisit2.getPageCodes();
        			queryPageCodes=StringUtils.replace(queryPageCodes, "[", "");
        			queryPageCodes=StringUtils.replace(queryPageCodes, "]", "");
					String[] split = StringUtils.split(queryPageCodes, ",");
					if(split !=null && split.length!=0){		
						for (String string : split) {
						String[] split2 = StringUtils.split(string, ":");
						if(split2.length==1){
							String count=split2[0];
							split2=new String[2];
							split2[0]=" ";
							split2[1]=count;
						}
						Boolean flag=false;
						if(pageVisitList!=null && pageVisitList.size()!=0){
							for (ResponseRobot res : pageVisitList) {
								
								if(res.getName().equals(PageCodeUtil.getPageName(split2[0], "/robot.properties")) ||(res.getName().equals("其它")&&StringUtils.isBlank(PageCodeUtil.getPageName(split2[0], "/robot.properties")))){
									flag=true;
									res.setCounts(res.getCounts()+Integer.valueOf(split2[1]));
								}
							}
						}
						if(!flag){
							ResponseRobot responseRobot=new ResponseRobot();
							String pageName = PageCodeUtil.getPageName(split2[0], "/robot.properties");
							if(StringUtils.isBlank(pageName)){
								responseRobot.setName("其它");
							}else{
							responseRobot.setName(pageName);
							}
							responseRobot.setCounts(Integer.valueOf(split2[1]));
							pageVisitList.add(responseRobot);
						}
					}}
					
				}
			}
		}
		Collections.sort(pageVisitList, new myComparator());
        Collections.reverse(pageVisitList);
		robotData.setPageVisitList(pageVisitList);
		
		List<ResponseRobot> resQuestionList=new ArrayList<>();
		if(frequentlyQuestionsList !=null && frequentlyQuestionsList.size() !=0){
            for (FrequentlyQuestion frequentlyQuestion : frequentlyQuestionsList) {
        		if(frequentlyQuestion!=null && StringUtils.isNotBlank(frequentlyQuestion.getQuestions())){
        			String queryQuestions=frequentlyQuestion.getQuestions();
        			queryQuestions=StringUtils.replace(queryQuestions, "[", "");
        			queryQuestions=StringUtils.replace(queryQuestions, "]", "");
        			String[] split = StringUtils.split(queryQuestions, ",");
        			if(split !=null && split.length!=0){
        				for (String string : split) {
        					String[] split2 = StringUtils.split(string, ":");
        					if(split2.length==1){
        						String count=split2[0];
        						split2=new String[2];
        						split2[0]=" ";
        						split2[1]=count;
        					}
        					
        					Boolean flag=false;
                            if(resQuestionList!=null && resQuestionList.size()!=0){
                                for (ResponseRobot res : resQuestionList) {
                                    if(res.getName().equals(split2[0]) || res.getName().equals(buttonMap.get(split2[0]))|| (res.getName().equals("其它")&&StringUtils.isBlank(split2[0]))){
                                        flag=true;
                                        res.setCounts(res.getCounts()+Integer.valueOf(split2[1]));
                                    }
                                }
                            }
                            
                            if(!flag){
            					if(split2!=null && split2.length!=0){
            						ResponseRobot responseRobot=new ResponseRobot();
            						if(StringUtils.isBlank(split2[0])){
            							responseRobot.setName("其它");
            						}else{
            							responseRobot.setName(split2[0]);
            						}
            						responseRobot.setCounts(Integer.valueOf(split2[1]));
            						resQuestionList.add(responseRobot);
            					}
                            }
        				}
        			}
        		}
            }
		}
		Collections.sort(resQuestionList, new myComparator());
        Collections.reverse(resQuestionList);
        if(resQuestionList!=null && resQuestionList.size()>10){
        	resQuestionList=resQuestionList.subList(0, 10);
        }
		robotData.setQuestionList(resQuestionList);
		
		//封装饼图数据
				List<PieRobot> questionPie=new ArrayList<>();
				if(robotData.getQuestionList()!=null && robotData.getQuestionList().size()!=0){
				for (ResponseRobot responseRobot : robotData.getQuestionList()) {
					PieRobot pieRobot=new PieRobot();
					pieRobot.setName(responseRobot.getName());
					pieRobot.setValue(responseRobot.getCounts());
					questionPie.add(pieRobot);
				}
				}
				robotData.setQuestionPie(questionPie);
		List<ResponseRobot> sourceVisitList = new ArrayList<>();
		if(sourceVisit !=null && sourceVisit.size() !=0){
			for (SourceVisit sourceVisit2 : sourceVisit) {
				if(sourceVisit2!=null && StringUtils.isNotBlank(sourceVisit2.getPageCodes())){
					String queryPageCodes=sourceVisit2.getPageCodes();
        			queryPageCodes=StringUtils.replace(queryPageCodes, "[", "");
        			queryPageCodes=StringUtils.replace(queryPageCodes, "]", "");
					String[] split = StringUtils.split(queryPageCodes, ",");
					if(split !=null && split.length!=0){		
						for (String string : split) {
						String[] split2 = StringUtils.split(string, ":");
						if(split2.length==1){
							String count=split2[0];
							split2=new String[2];
							split2[0]=" ";
							split2[1]=count;
						}
						Boolean flag=false;
						if(sourceVisitList!=null && sourceVisitList.size()!=0){
							for (ResponseRobot res : sourceVisitList) {
								if(res.getName().equals(PageCodeUtil.getPageName(split2[0],"/robot.properties")) ||(res.getName().equals("其它")&&StringUtils.isBlank(PageCodeUtil.getPageName(split2[0],"/robot.properties")))){
									flag=true;
									res.setCounts(res.getCounts()+Integer.valueOf(split2[1]));
								}
							}
						}
						
						if(!flag){
							ResponseRobot responseRobot=new ResponseRobot();
							String pageName = PageCodeUtil.getPageName(split2[0],"/robot.properties");
							if(StringUtils.isBlank(pageName)){
								responseRobot.setName("其它");
							}else{
								responseRobot.setName(pageName);
							}
							responseRobot.setCounts(Integer.valueOf(split2[1]));
							sourceVisitList.add(responseRobot);
						}
					}}
					
				}
			}
		}
		Collections.sort(sourceVisitList, new myComparator());
        Collections.reverse(sourceVisitList);
		robotData.setSourceVisitList(sourceVisitList);
		robotData.setArea("全国");
		robotData.setStartDate(start);
		robotData.setEndDate(end);
		return robotData;
		
	}
	
	
	public Map<String,String> getButtonMap() throws ClientProtocolException, IOException{
		HttpGet httpGet=new HttpGet(url);
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse response=null;
		response=httpClient.execute(httpGet);
		Map<String,String> map=new HashMap<String, String>();
		if (response.getStatusLine().getStatusCode() == 200) {
            String json= EntityUtils.toString(response.getEntity(),"UTF-8");
            RobotButton robotButton = MAPPER.readValue(json,RobotButton.class);
            if(robotButton !=null && robotButton.getData() !=null &&robotButton.getData().size()!=0){
            	for (ButtonName buttonName:robotButton.getData()) {
            		map.put(buttonName.getCode(), buttonName.getName());
				}
            }
        }
		
		return map;
	}

}

class myComparator implements Comparator<ResponseRobot>{
    @Override
    public int compare(ResponseRobot o1, ResponseRobot o2) {
        
        return o1.getCounts().compareTo(o2.getCounts());
    }
    
}
